import axios from 'axios'
import Config from '@/settings'

const downloadService = axios.create({
  baseURL: '',
  timeout: Config.timeout // 请求超时时间
})
downloadService.interceptors.response.use(response => response.data)

export function downloadUrl(url) {
  return downloadService({
    baseURL: '',
    url: url,
    headers: {
      'content-type': 'multipart/form-data'
    },
    method: 'get'
  })
}

export function downloadUrlByAjax(options) {
  options = options || {}
  const xhr = new XMLHttpRequest()
  if (options.type === 'file') {
    xhr.responseType = 'arraybuffer'
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      const status = xhr.status
      if (status >= 200 && status < 300) {
        options.success && options.success(xhr.response)
      } else {
        options.fail && options.fail(status)
      }
    }
  }
  xhr.open('GET', options.url, true)
  xhr.send(null)
}
export default { downloadUrl, downloadUrlByAjax }
